﻿using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

namespace AdTech.Snap
{
    /// <summary>
    /// A Dropbox library used mainly to generated public links of files.
    /// </summary>
    public class DropboxFactory : IDropboxFactory
    {
        // Fields
        private string _RelativeLocation;
        /// <summary>
        /// Returns the Dropbox Public Link Format.
        /// </summary>
        public const string PublicLinkFormat = "http://dl.dropbox.com/u/{0}/{1}";
        private const string PublicLinkPattern = "^http://dl.dropbox.com/u/([0-9]+)/.*$";

        // Properties
        /// <summary>
        /// Gets or sets the Dropbox UserID.
        /// </summary>
        public int UserID { get; set; }
        /// <summary>
        /// Gets or sets the file location that a public link should point to.
        /// </summary>
        public string Location { get; set; }
        /// <summary>
        /// Gets the path end relative to the Dropbox public folder.
        /// </summary>
        public string RelativeLocation
        {
            get 
            {
                if (this._RelativeLocation == null)
                    this._RelativeLocation = this.GetRelativeToRoot();
                return this._RelativeLocation;
            }
        }

        // Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="AdTech.Snap.DropboxFactory"/> class.
        /// </summary>
        public DropboxFactory(int userID, string dropboxlocation)
        {
            this.UserID = userID;
            this.Location = dropboxlocation;
        }

        // Public Methods
        /// <summary>
        /// Creates a new instance of the <see cref="AdTech.Snap.DropboxFactory"/> class.
        /// </summary>
        public static IDropboxFactory Create(int userID, string dropboxlocation)
        {
            return new DropboxFactory(userID, dropboxlocation);
        }

        #region IDropboxFactory Members
        /// <summary>
        /// Generates a public Dropbox link for an existing file.
        /// </summary>
        /// <param name="filepath">The path of the file.</param>
        /// <returns>A <see cref="System.Uri"/> of the public link.</returns>
        /// <remarks>
        /// This method just creates string including the given file 
        /// path and does not check whether the file actually exists.
        /// </remarks>
        public Uri GenerateDropboxPublicLink(string filepath)
        {
            string relativePath = Path.Combine(this.RelativeLocation, Path.GetFileName(filepath));
            string url = String.Format(PublicLinkFormat, this.UserID, relativePath);
            return new Uri(url);
        }

        /// <summary>
        /// Tries to extract the Dropbox UserID from a public URL.
        /// </summary>
        /// <param name="publicURL">A public URL generated through Dropbox.</param>
        /// <returns>The extracted UserID or 0 if it could not be extracted.</returns>
        public int ExtractUserID(string publicURL)
        {
            Match match = Regex.Match(publicURL, PublicLinkPattern);
            string result = match.Groups.Cast<Group>().Select(x => x.Value).LastOrDefault();
            int userID = 0;
            if (!String.IsNullOrEmpty(result))
                Int32.TryParse(result, out userID);
            return userID;
        }
        #endregion

        // Protected Methods
        /// <summary>
        /// Gets a string of the path end relative to the Dropbox public folder.
        /// </summary>
        /// <returns>A <see cref="System.String"/> of the relative path.</returns>
        protected string GetRelativeToRoot()
        {
            string pubFolder = @"Dropbox\Public";
            int pubFolderStart = this.Location.Trim(Path.DirectorySeparatorChar).LastIndexOf(pubFolder);
            int pubFolderEnd = pubFolderStart >= 0 ? pubFolderStart + pubFolder.Length + 1 : -1;
            string customDirRoot = pubFolderEnd >= 0 && pubFolderEnd <= this.Location.Length ? this.Location.Substring(pubFolderEnd) : String.Empty;
            if (String.IsNullOrEmpty(customDirRoot))
                throw new ArgumentException(String.Format("Could not find public dropbox folder using '{0}'", pubFolder));
            return customDirRoot;
        }
    }
}
